<template>
  <view class="container">
    <!--  -->
    <view class="status-bar"></view>
    <!-- 聊天内容区域 -->
    <view class="chat-content">
      <!-- 常用联系人 -->
      <view class="contact-list">
        <view class="section-title">常用联系人</view>
        <view class="contacts">
          <view
            class="contact-item"
            v-for="contact in contacts"
            :key="contact.id"
            @click="selectContact(contact)"
          >
            <view class="avatar">
              <image :src="contact.avatar" mode="aspectFill" class="avatar-img"></image>
            </view>
            <view class="contact-name">{{ contact.name }}</view>
            <view class="contact-relation">{{ contact.relation }}</view>
          </view>
        </view>
      </view>

      <!-- 聊天记录 -->
      <scroll-view class="chat-history" scroll-y="true" :scroll-into-view="scrollToView">
        <view v-for="(messageGroup, index) in messageGroups" :key="index">
          <view class="message-time">{{ messageGroup.time }}</view>
          <view
            v-for="message in messageGroup.messages"
            :key="message.id"
            class="message-item"
            :class="message.type === 'sent' ? 'message-item-sent' : 'message-item-received'"
            :id="'message-' + message.id"
          >
            <!-- 接收的消息（左侧显示） -->
            <view v-if="message.type === 'received'" class="message-left">
              <image :src="message.avatar" mode="aspectFill" class="message-avatar"></image>
              <view class="message-content">
                <view class="message-sender"
                  >{{ message.sender }}{{ message.showTime ? ' ' + message.time : '' }}</view
                >
                <view class="message-bubble message-received">
                  {{ message.content }}
                </view>
              </view>
            </view>

            <!-- 发送的消息（右侧显示） -->
            <view v-else class="message-right">
              <view class="message-content">
                <view class="message-sender message-sender-right"
                  >{{ message.sender }}{{ message.showTime ? ' ' + message.time : '' }}</view
                >
                <view class="message-bubble message-sent">
                  {{ message.content }}
                </view>
              </view>
              <image :src="message.avatar" mode="aspectFill" class="message-avatar"></image>
            </view>
          </view>
        </view>
      </scroll-view>
    </view>

    <!-- 输入区域 -->
    <view class="input-area">
      <view class="input-container">
        <input
          type="text"
          class="input-box"
          placeholder="请输入消息"
          v-model="inputMessage"
          @confirm="sendMessage"
        />
      </view>
      <button class="send-btn" @click="sendMessage">发送</button>
    </view>
  </view>
</template>

<script setup>
import { ref, reactive, nextTick } from 'vue';

// 输入的消息
const inputMessage = ref('');

// 滚动到指定消息
const scrollToView = ref('');

// 当前用户身份（根据图片，用户是"女儿"）
const currentUser = ref('女儿');

// 联系人列表
const contacts = reactive([
  {
    id: 1,
    name: '张女士',
    relation: '女儿',
    avatar:
      'https://tse3-mm.cn.bing.net/th/id/OIP-C.ayJhT1Fqevx90pIUni-GrgHaHa?w=189&h=189&c=7&r=0&o=7&cb=ucfimgc2&dpr=2&pid=1.7&rm=3',
  },
  {
    id: 2,
    name: '李先生',
    relation: '儿子',
    avatar:
      'https://images.unsplash.com/photo-1507003211169-0a1dd7228f2d?w=150&h=150&fit=crop&crop=face',
  },
  {
    id: 3,
    name: '王医生',
    relation: '主治医师',
    avatar:
      'https://images.unsplash.com/photo-1612349317150-e413f6a5b16d?w=150&h=150&fit=crop&crop=face',
  },
]);

// 消息分组 - 根据图片内容重新组织
const messageGroups = reactive([
  {
    time: '今天 10:30',
    messages: [
      {
        id: 1,
        sender: '女儿',
        content: '爸爸，今天吃药了吗？血压怎么样？',
        type: 'received', // 用户自己发送的消息
        time: '10:30',
        showTime: false,
        avatar:
          'https://tse3-mm.cn.bing.net/th/id/OIP-C.ayJhT1Fqevx90pIUni-GrgHaHa?w=189&h=189&c=7&r=0&o=7&cb=ucfimgc2&dpr=2&pid=1.7&rm=3',
      },
      {
        id: 2,
        sender: '',
        content: '吃过了，血压有点高，135/85',
        type: 'send',
        time: '10:30',
        showTime: true,
        avatar:
          'https://tse1-mm.cn.bing.net/th/id/OIP-C.daqf3JooB2ffRyx4NPnvwQHaFS?w=189&h=135&c=7&r=0&o=7&cb=ucfimgc2&dpr=2&pid=1.7&rm=3',
      },
    ],
  },
  {
    time: '今天 14:15',
    messages: [
      {
        id: 3,
        sender: '王医生',
        content: '张先生，请注意休息，明天记得复查',
        type: 'received',
        time: '14:15',
        showTime: true,
        avatar:
          'https://images.unsplash.com/photo-1612349317150-e413f6a5b16d?w=100&h=100&fit=crop&crop=face',
      },
    ],
  },
]);

// 发送消息
const sendMessage = () => {
  if (!inputMessage.value.trim()) return;

  const newMessage = {
    id: Date.now(),
    sender: currentUser.value, // 使用当前用户身份
    content: inputMessage.value,
    type: 'sent', // 用户发送的消息类型为sent
    time: getCurrentTime(),
    showTime: true,
    avatar:
      'https://images.unsplash.com/photo-1535713875002-d1d0cf377fde?w=100&h=100&fit=crop&crop=face',
  };

  // 添加到今天的消息组，如果没有今天的组就创建
  const todayGroup = messageGroups.find((group) => group.time.includes('今天'));
  if (todayGroup) {
    todayGroup.messages.push(newMessage);
  } else {
    messageGroups.push({
      time: '今天 ' + getCurrentTime(),
      messages: [newMessage],
    });
  }

  inputMessage.value = '';
  scrollToBottom();
};

// 获取当前时间
const getCurrentTime = () => {
  const now = new Date();
  return `${now.getHours().toString().padStart(2, '0')}:${now
    .getMinutes()
    .toString()
    .padStart(2, '0')}`;
};

// 滚动到底部
const scrollToBottom = () => {
  nextTick(() => {
    const lastMessage = messageGroups[messageGroups.length - 1]?.messages;
    if (lastMessage && lastMessage.length > 0) {
      scrollToView.value = 'message-' + lastMessage[lastMessage.length - 1].id;
    }
  });
};

// 选择联系人
const selectContact = (contact) => {
  uni.showToast({
    title: `开始与${contact.name}聊天`,
    icon: 'none',
  });
};
</script>

<style scoped>
.status-bar {
  height: 64rpx;
}
.container {
  background-color: #f5f5f5;
  min-height: 100vh;
  position: relative;
  padding-bottom: 160rpx;
}

/* 聊天内容区域 */
.chat-content {
  padding: 30rpx;
  min-height: calc(100vh - 280rpx);
}

.contact-list {
  margin-bottom: 40rpx;
  background: white;
  border-radius: 20rpx;
  padding: 30rpx;
  box-shadow: 0 4rpx 12rpx rgba(0, 0, 0, 0.05);
}

.section-title {
  font-size: 36rpx; /* 增大字体 */
  color: #333;
  margin-bottom: 30rpx;
  font-weight: 600;
}

.contacts {
  display: flex;
  justify-content: space-between;
}

.contact-item {
  display: flex;
  flex-direction: column;
  align-items: center;
  width: 30%;
}

.avatar {
  width: 140rpx; /* 增大头像尺寸 */
  height: 140rpx;
  border-radius: 50%;
  background-color: #f0f0f0;
  display: flex;
  align-items: center;
  justify-content: center;
  margin-bottom: 20rpx;
  overflow: hidden;
  border: 4rpx solid #e8f4ff;
}

.avatar-img {
  width: 100%;
  height: 100%;
  border-radius: 50%;
}

.contact-name {
  font-size: 32rpx; /* 增大字体 */
  margin-bottom: 8rpx;
  font-weight: 500;
  color: #333;
}

.contact-relation {
  font-size: 28rpx; /* 增大字体 */
  color: #999;
  background: #f8f9fa;
  padding: 6rpx 18rpx; /* 增大内边距 */
  border-radius: 12rpx;
}

/* 聊天记录 */
.chat-history {
  height: 800rpx;
  margin-top: 40rpx;
  background: white;
  border-radius: 20rpx;
  padding: 30rpx;
  box-shadow: 0 4rpx 12rpx rgba(0, 0, 0, 0.05);
}

.message-item {
  margin-bottom: 40rpx;
}

/* 接收的消息（左侧布局） */
.message-left {
  display: flex;
  align-items: flex-start;
  gap: 20rpx;
}

/* 发送的消息（右侧布局） */
.message-right {
  display: flex;
  align-items: flex-start;
  justify-content: flex-end;
  gap: 20rpx;
}

.message-avatar {
  width: 100rpx; /* 增大头像尺寸 */
  height: 100rpx;
  border-radius: 50%;
  flex-shrink: 0;
}

.message-content {
  flex: 1;
  min-width: 0;
  max-width: 70%;
}

.message-sender {
  font-size: 28rpx; /* 增大字体 */
  color: #999;
  margin-bottom: 8rpx;
  padding-left: 10rpx;
}

.message-sender-right {
  text-align: right;
  padding-right: 10rpx;
  padding-left: 0;
}

.message-time {
  text-align: center;
  font-size: 28rpx; /* 增大字体 */
  color: #999;
  margin: 30rpx 0;
  background: #f8f9fa;
  padding: 10rpx 24rpx; /* 增大内边距 */
  border-radius: 20rpx;
  display: inline-block;
  margin-left: 50%;
  transform: translateX(-50%);
}

.message-bubble {
  padding: 24rpx 28rpx; /* 增大内边距 */
  border-radius: 20rpx;
  font-size: 32rpx; /* 增大字体 */
  line-height: 1.4;
  word-break: break-word;
  position: relative;
}

.message-received {
  background-color: #f0f2f5;
  border-top-left-radius: 8rpx;
  color: #333;
  margin-right: auto;
}

.message-sent {
  background: linear-gradient(135deg, #4a90e2, #357ae8);
  color: white;
  border-top-right-radius: 8rpx;
  margin-left: auto;
  text-align: left;
}

/* 输入区域 */
.input-area {
  position: fixed;
  bottom: 0;
  left: 0;
  right: 0;
  background-color: white;
  padding: 20rpx 30rpx;
  border-top: 1px solid #eaeaea;
  display: flex;
  align-items: center;
  gap: 20rpx;
  box-shadow: 0 -4rpx 12rpx rgba(0, 0, 0, 0.05);
}

.input-container {
  flex: 1;
  display: flex;
  align-items: center;
  background: #f8f9fa;
  border-radius: 40rpx;
  padding: 0 30rpx;
}

.input-box {
  flex: 1;
  background: transparent;
  border: none;
  padding: 24rpx 0; /* 增大内边距 */
  font-size: 32rpx; /* 增大字体 */
  height: auto;
  min-height: auto;
}

.input-box:focus {
  outline: none;
}

.send-btn {
  background: linear-gradient(135deg, #4a90e2, #357ae8);
  color: white;
  border: none;
  border-radius: 40rpx;
  padding: 24rpx 48rpx; /* 增大内边距 */
  font-size: 32rpx; /* 增大字体 */
  font-weight: 500;
  flex-shrink: 0;
  box-shadow: 0 4rpx 12rpx rgba(74, 144, 226, 0.3);
}

.send-btn:active {
  transform: scale(0.98);
}
</style>
